#! /usr/bin/python3
# -*- coding: UTF-8 -*-

if __name__ == "__main__":
	raise Exception("不支持从这里调用")

__version__ = "1.0"
__all__ = ["MouseChshDbModel"]

from com.mousechsh.common.data.MouseChshField import MouseChshField
from com.mousechsh.common.data.MouseChshModel import MouseChshModel


class MouseChshDbModelMeta(type):

	def __new__(mcs, name, bases, attrs):
		if name == 'MouseChshModel':
			return type.__new__(mcs, name, bases, attrs)
		mapping = attrs.get('__mousechsh_mapping__', {})
		db_column = attrs.get('__mousechsh_db_column__', {})
		for key, value in attrs.items():
			if isinstance(value, MouseChshField):
				mapping[key] = value
				db_column[value.get_key()] = key
		for key in mapping.keys():
			attrs.pop(key)
		for base in bases:
			b_ojb = base()
			if isinstance(b_ojb, MouseChshModel) and hasattr(b_ojb, '__mousechsh_mapping__') and hasattr(
				b_ojb, '__mousechsh_db_column__'
			):
				mapping = dict(mapping, **b_ojb.__mousechsh_mapping__)
				db_column = dict(db_column, **b_ojb.__mousechsh_db_column__)
		attrs['__mousechsh_mapping__'] = mapping
		attrs['__mousechsh_db_column__'] = db_column

		meta = attrs.get('Meta')
		if meta is None:
			attrs['__mousechsh_table_name__'] = name
		else:
			meta_obj = meta()
			if getattr(meta_obj, 'TableName', None) is None or meta_obj.TableName is None:
				attrs['__mousechsh_table_name__'] = name
			else:
				attrs['__mousechsh_table_name__'] = meta_obj.TableName
			if getattr(meta_obj, 'SchemaName', None) is None or meta_obj.SchemaName is None:
				attrs['__mousechsh_schema_name__'] = name
			else:
				attrs['__mousechsh_schema_name__'] = meta_obj.SchemaName

		return type.__new__(mcs, name, bases, attrs)


class MouseChshDbModel(MouseChshModel, metaclass=MouseChshDbModelMeta):

	def get_schema_name(self):
		return self.__mousechsh_schema_name__

	def get_table_name(self):
		return self.__mousechsh_table_name__

	def get_full_table_name(self):
		return \
			(
				self.__mousechsh_schema_name__ + '.' if self.__mousechsh_schema_name__ else ''
			) + self.__mousechsh_table_name__

	def get_attr_by_column_name(self, name):
		return self.__mousechsh_db_column__.get(name, None)

	def get_attr_by_name(self, name):
		return self.__mousechsh_mapping__.get(name, None)

	def set_data(self, data):
		if isinstance(data, dict):
			for key in data:
				if self.get_attr_by_name(key) is not None:
					setattr(self, key, data[key])
